/* eslint-disable react/display-name */
import { Button, Row, Input, Form, Space, Drawer, Table } from "antd";
import React, { useState, useRef, memo, forwardRef, useImperativeHandle } from "react";
import { v4 as uuidv4 } from "uuid";
import { ProductDTO, productSave, productView } from "./productApi";

// 新增 or 编辑 商品
export default memo(
	forwardRef(function FormDrawer(props: DataUpdate<ProductDTO>, ref: any) {
		const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
		const [open, setOpen] = useState<boolean>(false);
		const [action, setAction] = useState<string>("添加");
		const [form] = Form.useForm();

		useImperativeHandle(ref, () => ({
			open: async (id: string) => {
				let isEdit = false;
				setAction("添加");
				if (id) {
					isEdit = true;
					setAction("编辑");
				}
				setOpen(true);				
				form.resetFields();
				isEdit ? editProduct(id) : addProduct();
			},
		}));

		// 新增商品
		const addProduct = () => {
			form.setFieldsValue({
				productId: uuidv4(),				
			});
			setSelectedRowKeys([]);
		};

		const editProduct = async (id: string) => {
			console.log(id);
			let res = await productView(id);
			form.setFieldsValue(res.data);
		};

		// 关闭抽屉
		const onClose = () => {
			setOpen(false);
		};

		//保存
		const onOK = async () => {
			var values = await form.validateFields();
			if (values) {
				let param = form.getFieldsValue();
				let res = await productSave(param);
				if (res.data && props.update) {
					props.update(res.data);
				}
				onClose();
			}
		};

		return (
			<Drawer
				title={action + "商品"}
				width={720}
				onClose={onClose}
				open={open}
				styles={{
					body: {
						paddingBottom: 80,
					},
				}}
				extra={
					<Space>
						<Button onClick={onClose}>取消</Button>
						<Button onClick={onOK} type="primary">
							提交
						</Button>
					</Space>
				}
			>
				<Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
					<Form.Item hidden name="productId" />
					
					<Form.Item name="productCode" label="商品编码" rules={[{ required: true, message: "请输入商品编码" }]}>
						<Input placeholder="请输入商品编码" />
					</Form.Item>
					<Form.Item name="productName" label="商品名称" rules={[{ required: true, message: "请输入商品名称" }]}>
						<Input placeholder="请输入商品名称" />
					</Form.Item>
					<Form.Item name="note" label="商品描述">
						<Input placeholder="请输入商品描述" />
					</Form.Item>
				</Form>
			</Drawer>
		);
	})
);
